package com.huaxin.hxcloud.fragment;

import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.InfoMainTypeListDTO;
import com.huaxin.common.Entity.InfoType;
import com.huaxin.common.Global;
import com.huaxin.common.message.view.GlideCircleImage;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.NewsListActivity;
import com.huaxin.hxcloud.find.BannerAdapter;
import com.huaxin.hxcloud.find.FindSearchActivity;
import com.huaxin.hxcloud.find.ReportSayActivity;
import com.huaxin.hxcloud.find.ViewpagerAdapter;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/7.
 *
 * 此fragment未被用到，可删除
 *
 */
public class InfoPagerFragment extends BaseFragment implements View.OnClickListener, OnItemClickListener {

    private ViewpagerAdapter mainTabFragmentAdapter;//fragment的适配器
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.appbar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.ll_header_layout)
    LinearLayout headerLayout;
    private static boolean isHideHeaderLayout = false;//是否隐藏了头部
    @BindView(R.id.tabs)
    TabLayout mTabs;
    @BindView(R.id.find_img_back)
    ImageView imgBack;
    @BindView(R.id.coor_banner_view)
    RollPagerView bannerView;
    @BindView(R.id.pager_info_list2_skip)
    TextView imgSkip;

    @BindView(R.id.find_search_tv)
    TextView searchTv;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_pager_info_list2;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        //
        if (Global.user != null) {
            if (Global.user.getOrgCode() == null) {
                mainTabFragmentAdapter = new ViewpagerAdapter(getChildFragmentManager(), getContext(), 1);//游客
            } else {
                mainTabFragmentAdapter = new ViewpagerAdapter(getChildFragmentManager(), getContext(), 2);//企业
            }
            mViewPager.setAdapter(mainTabFragmentAdapter);
            mViewPager.setOffscreenPageLimit(mainTabFragmentAdapter.getCount());
            mTabs.setupWithViewPager(mViewPager);
        }
        initAppBarLayout();
        //
        topList.setLayoutManager(new GridLayoutManager(getContext(), 5));
        topAdapter = new TopAdapter();
        topList.setAdapter(topAdapter);
        //
        imgBack.setOnClickListener(this);
        imgSkip.setOnClickListener(this);

        searchTv.setOnClickListener(this);
        //
        bannerView.setAnimationDurtion(1000);
        bannerView.setAdapter(new BannerAdapter());
    }

    @Override
    public void onItemClick(int position) {
    }

    // 初始化AppBarLayout
    private void initAppBarLayout() {
        //添加View时过渡动画效果
        LayoutTransition mTransition = new LayoutTransition();
        ObjectAnimator addAnimator = ObjectAnimator.ofFloat(null, "translationY", 0, 1.0f).setDuration(mTransition.getDuration(LayoutTransition.APPEARING));
        mTransition.setAnimator(LayoutTransition.APPEARING, addAnimator);
        mAppBarLayout.setLayoutTransition(mTransition);

        final int headerHeight = getResources().getDimensionPixelOffset(R.dimen.header_height);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                verticalOffset = Math.abs(verticalOffset);
                if (verticalOffset >= headerHeight) {
                    isHideHeaderLayout = true;
                    //当偏移量超过顶部layout的高度时，我们认为他已经完全移动出屏幕了
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) headerLayout.getLayoutParams();
                            mParams.setScrollFlags(0);
                            headerLayout.setLayoutParams(mParams);
                            headerLayout.setVisibility(View.GONE);
                            imgBack.setVisibility(View.VISIBLE);
                            setLoadMore();
                        }
                    }, 300);
                } else {
                }
            }
        });
    }

    private void setLoadMore() {
//        ((FindFragment) mainTabFragmentAdapter.getFragments().get(mViewPager.getCurrentItem())).getRvList().scrollToPosition(0);
        for (int i = 0; i < mViewPager.getChildCount(); i++) {
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getxRefreshView().setPullLoadEnable(true);
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getxRefreshView().setEnabled(true);
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getxRefreshView().setAutoRefresh(true);
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getLayoutManager().setSpeedRatio(1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_img_back:
                scrollheader();
                break;
            case R.id.pager_info_list2_skip:
                startActivityForResult(new Intent(getContext(), ReportSayActivity.class), 0);
                break;
            case R.id.find_search_tv:
                Intent intent = new Intent(getContext(), FindSearchActivity.class);
                startActivity(intent);
                break;
        }

    }

    private void scrollheader() {
        //监听返回键
        if (isHideHeaderLayout) {
            isHideHeaderLayout = false;
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(mViewPager.getCurrentItem())).getRvList().scrollToPosition(0);
            headerLayout.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) headerLayout.getLayoutParams();
                    mParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
                    headerLayout.setLayoutParams(mParams);
                    imgBack.setVisibility(View.INVISIBLE);
                    setLoadMorefalse();
                }
            }, 300);
        } else {
        }
    }

    private void setLoadMorefalse() {
        for (int i = 0; i < mViewPager.getChildCount(); i++) {
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getxRefreshView().setPullLoadEnable(false);
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getxRefreshView().setEnabled(false);
//            ((FindFragment) mainTabFragmentAdapter.getFragments().get(i)).getLayoutManager().setSpeedRatio(0);
        }
    }


    @BindView(R.id.top_list)
    RecyclerView topList;
    private List<InfoType> _topTypes = new ArrayList();

    private TopAdapter topAdapter;
    private InfoMainTypeListDTO _infoMainTypeList;

    @Override
    public void requestData() {
        String temp = getACache().getAsString(Constants.AC_MAIN_INFO_TYPE);
        if (temp != null) {
            _infoMainTypeList = getGson().fromJson(
                    temp, InfoMainTypeListDTO.class);
            updateView();
        } else {
            ApiRequestData(LOADING, null);
        }
    }

    public void updateView() {
        String temp = getACache().getAsString(Constants.AC_MAIN_INFO_TYPE);
        if (temp != null) {
            _infoMainTypeList = getGson().fromJson(
                    temp, InfoMainTypeListDTO.class);
        }
        if (_infoMainTypeList == null)
            return;
        List<InfoType> infoTypeList = _infoMainTypeList.getInfoTypes();
        _topTypes.clear();
        for (InfoType infoType : infoTypeList) {
            _topTypes.add(infoType);
        }
        topAdapter.notifyDataSetChanged();
    }

    //    //    //
    private void ApiRequestData(int status, final PullToRefreshBase<RecyclerView> refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<InfoMainTypeListDTO> call = getRequestApi().getMainInfoType();
        autoClose(call);
        call.enqueue(new Callback<InfoMainTypeListDTO>() {
            @Override
            public void onResponse(Call<InfoMainTypeListDTO> call, Response<InfoMainTypeListDTO>
                    response) {
                if (response.isSuccessful()) {
                    InfoMainTypeListDTO infoMainTypeListDto = response.body();
                    if (infoMainTypeListDto != null && infoMainTypeListDto.isSuccessful()) {
                        if (refreshView != null) {
                            refreshView.onRefreshComplete();
                        } else {
                            updateLoadStatus(LOAD_SUCCESS);
                        }
                        getACache().put(Constants.AC_MAIN_INFO_TYPE, getGson().toJson(infoMainTypeListDto));
                        updateView();
                        return;
                    }
                }
                if (refreshView != null) {
                    refreshView.onRefreshComplete();
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
                ToastUtil.showToast("数据异常");

            }

            @Override
            public void onFailure(Call<InfoMainTypeListDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
                if (refreshView != null) {
                    refreshView.onRefreshComplete();
                } else {
                    updateLoadStatus(LOAD_FAILURE);
                }

            }
        });
    }

    /**
     * 头部网格分类的适配器
     */
    public class TopAdapter extends RecyclerView.Adapter<TopAdapter.TopViewHolder> {

        @Override
        public TopViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new TopViewHolder(mInflater.inflate(R.layout.item_top_info, parent, false));
        }

        @Override
        public void onBindViewHolder(TopViewHolder holder, int position) {
            holder.update(position);
        }

        @Override
        public int getItemCount() {
            return _topTypes == null ? 0 : (_topTypes.size() < 10 ? _topTypes.size() : 10);
        }

        public class TopViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.ci1)
            ImageView ci1;
            @BindView(R.id.tv1)
            TextView tv1;

            View itemView;
            int position;

            public TopViewHolder(View itemView) {
                super(itemView);
                autoClose(ButterKnife.bind(this, itemView));
                this.itemView = itemView;
            }


            public void update(int position) {
                this.position = position;
                InfoType data = _topTypes.get(position);
                loadText(tv1, data.getTitle());
                itemView.setOnClickListener(this);

                Glide.with(getContext()).load(data.getImg())
                        .apply(new RequestOptions().transform(new GlideCircleImage()).placeholder(R.drawable.head_portrait)).into(ci1);

               /* getGlide().load(data.getImg())
                        .transform(new GlideCircleImage(getContext()))
                        .placeholder(R.drawable.head_portrait)
                        .into(ci1);*/
            }

            @Override
            public void onClick(View v) {
                InfoType data = _topTypes.get(position);
                NewsListActivity.start(getContext(), data);
            }
        }
    }

}
